var votebuttons = [];
    
function addListener(element, type, expression) {
    if(window.addEventListener)	{
        element.addEventListener(type, expression, false);
    } else if(window.attachEvent) {
        element.attachEvent('on' + type, expression);
    }
}
    
function getUserVoteKey(id) {
    return 'vote:' + id;
}

function configure_button_click() {
    var state = wave.getState();
    if(wave.getHost().getId() != wave.getViewer().getId()) return;
    
    var delta = {};
    delta['allow_multiple_selection'] = document.getElementById('allow_multiple_selection').checked ? 1 : 0;
    delta['show_results_always'] = document.getElementById('show_results_always').checked ? 1 : 0;
    delta['allow_vote_changes'] = document.getElementById('allow_vote_changes').checked ? 1 : 0;
    delta['polloptions'] = document.getElementById('pollitems').value;
    delta['setup_done'] = 1;
    state.submitDelta(delta);
}

function vote_button_enable() {
    var enable = false;
    
    for(var i in votebuttons) {
        if(votebuttons[i].checked) { enable = true; break; }
    }
    
    document.getElementById('vote_button').disabled = !enable;
    document.getElementById('result_vote_button').disabled = !enable;
}

function vote_button_click() {
    var state = wave.getState();
    
    var delta = {};
    
    var selections = new Array();
    
    for(var i in votebuttons) {
        if(votebuttons[i].checked) {
            selections.push(votebuttons[i].value);
            if (state.get('allow_multiple_selection') != true) break;
        }
    }
    
    if(selections.length > 0) {
        delta[getUserVoteKey(wave.getViewer().getId())] = (selections.length == 1) ? selections[0] : selections.join(",");
        
        state.submitDelta(delta);
    } else if(state.get('allow_multiple_selection')) {
        delta[getUserVoteKey(wave.getViewer().getId())] = null;
        state.submitDelta(delta);
    }
}

function inList(item, list) {
    list = list.split(",");
    for (var i in list) {
        if (list[i] == "") continue;
        if (list[i] == item) return true;
    }
    return false;
}

function stateUpdated() {
    var state = wave.getState();
    if (state !== null) {
        var confform = document.getElementById('configureform');
        confform.style.display = "none";
        var voteform = document.getElementById('voteform');
        voteform.style.display = "none";
        var resultform = document.getElementById('resultform');
        resultform.style.display = "none";
            
        if (state.get('setup_done') === null) {
            confform.style.display = "block";
            if (wave.getHost().getId() != wave.getViewer().getId() || wave.getMode() == wave.Mode.PLAYBACK) {
                while (confform.lastChild !== null) {
                    confform.removeChild(confform.lastChild);
                }
                confform.appendChild(document.createTextNode((wave.getMode() != wave.Mode.PLAYBACK)? "This poll still needs to be configured by the owner." : "This poll was not yet configured at this time."));
            }
        } else {
            var userresponse = state.get(getUserVoteKey(wave.getViewer().getId()));
            var polloptions = state.get('polloptions').split("\n");
            
            var curselections = "";
            if(votebuttons.length > 0 && wave.getMode() != wave.Mode.PLAYBACK) {
                curselections = new Array();
                
                for(var i in votebuttons) {
                    if(votebuttons[i].checked) {
                        curselections.push(votebuttons[i].value);
                        if (state.get('allow_multiple_selection') != true) break;
                    }
                }
                curselections = curselections.join(",");
            }
            
            if(state.get('show_results_always') == true || userresponse !== null) {
                resultform.style.display = "block";
                var pollresultstable = document.getElementById('pollresults');
                while (pollresultstable.lastChild !== null) {
                    pollresultstable.removeChild(pollresultstable.lastChild);
                }
                var resultcount = [];
                for (var i = 0; i < polloptions.length; i++) {
                    resultcount[i] = 0;
                }
                var totalresults = 0;
                var participants = wave.getParticipants();
                for (var i in participants) {
                    var p = participants[i];
                    var presponce = state.get(getUserVoteKey(p.getId()));
                    if (presponce === null) continue;
                    
                    presponce = presponce.split(",");
                    for (var item in presponce) {
                        resultcount[parseInt(presponce[item],10)]++;
                        if(state.get('allow_multiple_selection') != true) break;
                    }
                    totalresults++;
                }
                votebuttons = [];
                for (var i = 0; i < polloptions.length; i++) {
                    var optionrow = document.createElement('tr');
                    var optionlabeltd = document.createElement('td');
                    var optionlabel = document.createElement('label');
                    var optionbutton = document.createElement('input');
                    var optioncount = document.createElement('td');
                    var optionbar = document.createElement('td');
                    var optionbarvalue = document.createElement('div');
                    optionlabeltd.appendChild(optionlabel);
                    optionlabel.appendChild(optionbutton);
                    optionrow.appendChild(optionlabeltd);
                    optionrow.appendChild(optioncount);
                    optionrow.appendChild(optionbar);
                    optionbar.appendChild(optionbarvalue);
                    
                    optionlabel.className = "label";
                    optioncount.className = "count";
                    optionbar.className = "bar";
                    
                    optionbutton.type = (state.get('allow_multiple_selection') == true) ? "checkbox" : "radio";
                    optionbutton.value = i;
                    optionbutton.name = "polloption";
                    if (userresponse !== null && inList(i, userresponse)) {
                        optionbutton.checked = true;
                        optionrow.className = "selected";
                    } else {
                        optionbutton.checked = inList(i, curselections);
                    }
                    if (state.get('show_results_always') == true && wave.getMode() != wave.Mode.PLAYBACK) {
                        if (userresponse !== null) {
                            if (state.get('allow_vote_changes') == false) { optionbutton.disabled = true; }
                            if ((i != userresponse || state.get('allow_multiple_selection') == true) && state.get('allow_vote_changes') == true) { addListener(optionbutton, 'change', vote_button_click); }
                            else { addListener(optionbutton, 'change', vote_button_enable); }
                        } else {
                            if (state.get('allow_vote_changes') == true) { addListener(optionbutton, 'change', vote_button_click); }
                            else { addListener(optionbutton, 'change', vote_button_enable); }
                        }
                        votebuttons[votebuttons.length] = optionbutton;
                    } else {
                        optionbutton.disabled = true;
                    }
                    
                    optionlabel.appendChild(document.createTextNode(polloptions[i]));
                    var percent = 0;
                    if (totalresults > 0) percent = (resultcount[i] / totalresults) * 100;
                    optioncount.appendChild(document.createTextNode(percent.toFixed(1) + "% (" + resultcount[i] + ")"));
                    optionbarvalue.style.width = percent + "%";
                    
                    pollresultstable.appendChild(optionrow);
                }
                
                var votebutton = document.getElementById('result_vote_button');
                if (userresponse !== null || state.get('allow_vote_changes') == true) {
                    votebutton.style.display = "none";
                } else {
                    votebutton.style.display = "block";
                    if (wave.getMode() == wave.Mode.PLAYBACK) votebutton.disabled = true;
                    else vote_button_enable();
                }
            } else {
                voteform.style.display = "block";
                var polloptionsul = document.getElementById('polloptions');
                while (polloptionsul.lastChild !== null) {
                    polloptionsul.removeChild(polloptionsul.lastChild);
                }
                votebuttons = [];
                for (var i = 0; i < polloptions.length; i++) {
                    var optionli = document.createElement('li');
                    var optionlabel = document.createElement('label');
                    var optionbutton = document.createElement('input');
                    optionli.appendChild(optionlabel);
                    optionlabel.appendChild(optionbutton);
                    optionlabel.appendChild(document.createTextNode(polloptions[i]));
                    
                    optionbutton.type = (state.get('allow_multiple_selection') == true) ? "checkbox" : "radio";
                    optionbutton.value = i;
                    optionbutton.name = "polloption";
                    optionbutton.checked = inList(i, curselections);
                    if (wave.getMode() != wave.Mode.PLAYBACK) {
                        addListener(optionbutton, 'change', vote_button_enable);
                    } else {
                        optionbutton.disabled = true;
                    }
                    votebuttons[votebuttons.length] = optionbutton;
                    
                    polloptionsul.appendChild(optionli);
                }
                if (wave.getMode() == wave.Mode.PLAYBACK) {
                    var votebutton = document.getElementById('vote_button');
                    votebutton.disabled = true;
                } else vote_button_enable();
            }
        }
        gadgets.window.adjustHeight();
    }
}

function init() {
    if (wave && wave.isInWaveContainer()) {
        addListener(document.getElementById('configure_button'), 'click', configure_button_click);
        addListener(document.getElementById('vote_button'), 'click', vote_button_click);
        addListener(document.getElementById('result_vote_button'), 'click', vote_button_click);
        
        wave.setStateCallback(stateUpdated);
        wave.setParticipantCallback(stateUpdated);
    }
}
gadgets.util.registerOnLoadHandler(init);